package com.example.interceptor;


import cn.hutool.json.JSONUtil;
import com.example.common.enums.KeyEnum;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.CustomException;
import com.example.constant.JwtClaimsConstant;
import com.example.context.BaseContext;
import com.example.pojo.entity.Admin;
import com.example.pojo.utils.LoginUser;
import com.example.properties.JwtProperties;
import com.example.utils.IpUtils;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * jwt令牌校验的拦截器
 * 商家端
 */
//@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 校验jwt
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        if (request.getRequestURI().equals("/login")) {
            //调用登录方法
            String ip = IpUtils.getIp();

            //UV中新增相关数据
            redisTemplate.opsForHyperLogLog().add(KeyEnum.UV, ip);
            //当前在线人数中新增数据
            redisTemplate.opsForSet().add(KeyEnum.ONLINE, ip);
            return true;
        }

        if (request.getRequestURI().equals("/logout")){
            //如果调用退出方法，说明当前用户退出了系统
            String ip = IpUtils.getIp();
            //将该ip数据从redis中删除
            redisTemplate.opsForSet().remove(KeyEnum.ONLINE, ip);
        }

        //1、从请求头中获取令牌  token
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long adminId = Long.valueOf(claims.get(JwtClaimsConstant.ADMIN_ID).toString());
            //在线程中设置当前登录的ID
            BaseContext.setCurrentId(adminId);

            //通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
